﻿using System;
using DevExpress.Web.ASPxUploadControl;
using System.IO;
using System.Text.RegularExpressions;

namespace ITViet.Web.App_Code
{
  public sealed class Utils
  {
    #region Properties
    private const string DefaultLoggingCategory = "General";
    private const string WebRegularExpression = "(https?://)?(([0-9a-z_!'().&=$%-]: )?[0-9a-z_!'().&=$%-]@)?(([0-9]{1,3}\\.){3}[0-9]{1,3}|([0-9a-z_!'()-]\\.)([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\.[a-z]{2,6})(:[0-9]{1,4})?((/?)|(/[0-9a-z_!*'().;?:@&=$,%#-])/?)$";
    private const string EVENT_TARGET = "__EVENTTARGET";
    private const string EVENT_ARGUMENT = "__EVENTARGUMENT";
    #endregion

    public static string ReduceString(string content, int stringLength)
    {
      string reduceString = content;
      if (stringLength > 0)
      {
        reduceString = string.Empty;
        string[] wordList = content.Split(string.Empty.ToCharArray());
        foreach (string word in wordList)
        {
          reduceString += word;
          if (reduceString.Length >= stringLength)
            break;
          reduceString += " ";
        }
        if (reduceString.Length >= stringLength)
          reduceString += "...";
      }
      return reduceString;
    }

    public static string FormatDate(object value)
    {
      DateTime dt;
      DateTime.TryParse(value.ToString(), out dt);
      if (dt > DateTime.MinValue)
        return dt.ToShortDateString() + " " + dt.ToString("HH:mm");
      return "";
    }

    public static string GetDateTimeNumber(DateTime date)
    {
      return date.ToString("ddMMyyyyhhmmss");
    }

    public static string SafeHtmlString(object value)
    {
      if (value == null || value == DBNull.Value)
        return string.Empty;
      string str = value.ToString();
      string[] specialCharacter = new string[] { "\\", "'", "\"" };
      string[] replaceCharacter = new string[] { "\\\\", "\\'", "&quot;" };
      for (int i = 0; i < specialCharacter.Length; i++)
      {
        str = str.Replace(specialCharacter[i], replaceCharacter[i]);
      }
      return str;
    }

    public static string SafeString(string text)
    {
      if (text == null) return null;
      text = text.Trim();
      return text.Length == 0 ? null : text.Replace("'", "''");
    }

    public static string FormatWebLink(string link)
    {
      if (!string.IsNullOrEmpty(link))
      {
        if (!link.ToLower().StartsWith("http://"))
        {
          link = "http://" + link;
        }
      }
      return link;
    }

    public static string EmbedObject(string file, string width, string height, string id)
    {
      string embed, src;
      string type = file.Substring(file.LastIndexOf('.') + 1);

      if (type == "swf" || type == "flv")
      {
        src = type == "swf" ? file : FolderDirector.SwfPlayer;
        embed = "<embed ";
        embed += (!string.IsNullOrEmpty(height)) ? "height=\"" + height + "\" " : string.Empty;
        embed += (!string.IsNullOrEmpty(width)) ? "width=\"" + width + "\" " : string.Empty;
        embed += "flashvars=\"";
        embed += "file=" + file + "\"";
        embed += "wmode=\"transparent\" allowscriptaccess=\"always\" allowfullscreen=\"true\" quality=\"high\"";
        embed += "name=\"player_" + id + "\" id=\"player_" + id + "\" style=\"\" src=\"" + src + "\"";
        embed += "type=\"application/x-shockwave-flash\">";
      }
      //else if (type == "avi")
      //{
      //  embed = "<embed type=\"application/x-mplayer2\" ";
      //  embed += "id=\"player_" + id + "\"";
      //  embed += "pluginspage=\"http://www.microsoft.com/isapi/redir.dll?prd=windows&sbp=mediaplayer&ar=Media&sba=Plugin&\" ";
      //  embed += "src=\"" + file + "\" ";
      //  embed += "wmode=opaque ";
      //  embed += "windowless=1 ";
      //  embed += "Name=MediaPlayer ";
      //  embed += "AutoStart=0 ";
      //  embed += "loop=0 ";
      //  embed += "Width=" + width + " Height=" + height + " transparentAtStart=1 ";
      //  embed += "animationAtStart=1 ";
      //  embed += "fullScreen=1 ";
      //  embed += "stretchToFit=1 ";
      //  embed += "uiMode=mini ";
      //  embed += "ShowControls=1 ";
      //  embed += "ShowPositionControls=0 ";
      //  embed += "ShowStatusBar=0 ";
      //  embed += "autoSize=1 ";
      //  embed += "displaySize=1></embed>";
      //}
      else
      {
        embed = "<img style=\"height: " + height + "px; ";
        embed += "width: " + width + "px;\" ";
        embed += "src=\"" + file + "\" alt=\"...\" ";
        embed += "id=\"videoContainer_" + id + "\">";
      }
      return embed;
    }

    public static string EmbedObject(string absoluteFile, string file, string width, string height, string id)
    {
      SWFFile swf = new SWFFile(absoluteFile);
      string embed, src;
      string type = file.Substring(file.LastIndexOf('.') + 1);

      if (type == "swf" || type == "flv")
      {
        src = type == "swf" ? file : FolderDirector.SwfPlayer;

        embed = "<embed ";
        embed += "height=\"";
        string heightTemp = (!string.IsNullOrEmpty(height)) ? height : Convert.ToInt32(swf.FrameHeight * Convert.ToInt32(width) / swf.FrameWidth).ToString();
        embed += heightTemp;
        embed += "\"";
        embed += (!string.IsNullOrEmpty(width)) ? "width=\"" + width + "\" " : string.Empty;
        embed += "flashvars=\"";
        embed += "file=" + file + "\"";
        embed += "wmode=\"transparent\" allowscriptaccess=\"always\" allowfullscreen=\"true\" quality=\"high\"";
        embed += "name=\"player_" + id + "\" id=\"player_" + id + "\" style=\"\" src=\"" + src + "\"";
        embed += "type=\"application/x-shockwave-flash\">";
      }

      //else if (type == "avi")
      //{
      //  embed = "<embed type=\"application/x-mplayer2\" ";
      //  embed += "id=\"player_" + id + "\"";
      //  embed += "pluginspage=\"http://www.microsoft.com/isapi/redir.dll?prd=windows&sbp=mediaplayer&ar=Media&sba=Plugin&\" ";
      //  embed += "src=\"" + file + "\" ";
      //  embed += "wmode=opaque ";
      //  embed += "windowless=1 ";
      //  embed += "Name=MediaPlayer ";
      //  embed += "AutoStart=0 ";
      //  embed += "loop=0 ";
      //  embed += "Width=" + width + " Height=" + height + " transparentAtStart=1 ";
      //  embed += "animationAtStart=1 ";
      //  embed += "fullScreen=1 ";
      //  embed += "stretchToFit=1 ";
      //  embed += "uiMode=mini ";
      //  embed += "ShowControls=1 ";
      //  embed += "ShowPositionControls=0 ";
      //  embed += "ShowStatusBar=0 ";
      //  embed += "autoSize=1 ";
      //  embed += "displaySize=1></embed>";
      //}
      else
      {
        embed = "<img style=\"height: " + height + "px; ";
        embed += "width: " + width + "px;\" ";
        embed += "src=\"" + file + "\" alt=\"...\" ";
        embed += "id=\"videoContainer_" + id + "\">";
      }
      return embed;
    }

    public static void WriteLog(string description, Exception ex)
    {
      Library.Logging.Logger.LogError(description, ex, DefaultLoggingCategory, null);
    }

    public static string GetFileName(string fileName)
    {
      string file = fileName;
      int index = fileName.LastIndexOf('/');
      if (index >= 0)
        file = fileName.Substring(index + 1);
      return file;
    }

    #region Upload File
    /// <summary>
    /// note: path is virtualpath
    /// </summary>
    /// <param name="uploadedFile"></param>
    /// <param name="uploadFolder"></param>
    /// <returns>return path of file when success else return empty</returns>
    public static string SavePostedFile(UploadedFile uploadedFile, string path)
    {
      if (uploadedFile.IsValid)
      {
        System.Web.HttpServerUtility server = System.Web.HttpContext.Current.Server;

        string folder = CreateFolderMonthNow(path);
        path += folder;
        string filename = uploadedFile.FileName;
        string type = filename.Substring(filename.LastIndexOf('.'));
        string time = DateTime.Now.ToString("ddMMyyyyhhmmssffff");
        string pathreturn = path + time + type;
        filename = server.MapPath(path) + time + type;
        try
        {
          uploadedFile.SaveAs(filename);
          if (pathreturn.Contains("~/"))
            pathreturn = pathreturn.Replace("~/", "");
          if (pathreturn.Contains("../"))
            pathreturn = pathreturn.Replace("../", "");
          return pathreturn;
        }
        catch (Exception ex)
        {
          WriteLog("Utils.cs::Save Posted File", ex);
          return string.Empty;
        }
      }
      return string.Empty;
    }
    /// <summary>
    /// note: filepath is virtual path 
    /// </summary>
    /// <param name="tempFile"></param>
    /// <param name="filePath"></param>
    /// <returns>return path of file when success else return empty</returns>
    public static string SaveFileFromTemp(string tempFile, string path)
    {
      System.Web.HttpServerUtility server = System.Web.HttpContext.Current.Server;
      string type = tempFile.Substring(tempFile.LastIndexOf('.'));
      string name = DateTime.Now.ToString("yyyyMMddHHmmssffff");
      string folder = CreateFolderMonthNow(path);
      path += folder;
      string pathreturn = path + name + type;
      path = server.MapPath(path) + name + type;
      try
      {
        if (File.Exists(tempFile))
        {
          File.Copy(tempFile, path, true);
          File.Delete(tempFile);
        }
        if (pathreturn.Contains("~/"))
          pathreturn = pathreturn.Replace("~/", "");
        if (pathreturn.Contains("../"))
          pathreturn = pathreturn.Replace("../", "");
        return pathreturn;
      }
      catch (Exception ex)
      {
        WriteLog("Utils.cs::Save File From Temp", ex);
        return string.Empty;
      }
    }

    #region Custom Folder Save
    /// <summary>
    /// note: path is virtual path
    /// </summary>
    /// <param name="path"></param>
    /// <returns>true if Directory exist else return false</returns>
    public static bool DirectoryIsExisted(string path)
    {
      System.Web.HttpServerUtility server = System.Web.HttpContext.Current.Server;
      path = server.MapPath(path);
      return Directory.Exists(path);
    }
    /// <summary>
    /// return string path of folder created when success else empty
    /// note: path is virtual path
    /// </summary>
    /// <param name="path">type string</param>
    public static string CreateFolderMonthNow(string path)
    {
      string name = DateTime.Now.ToString("MM");
      System.Web.HttpServerUtility server = System.Web.HttpContext.Current.Server;
      if (!DirectoryIsExisted(path))
        throw new Exception(string.Format(Resources.Messages.ERR0066, path));

      string endpath = CreateFolderYearNow(path) + "/" + name + "/";// endpath contain path of year/month/
      path += endpath;
      if (DirectoryIsExisted(path))
        return endpath;
      path = server.MapPath(path);
      try
      {
        Directory.CreateDirectory(path);
        return endpath;
      }
      catch (Exception ex)
      {
        WriteLog("Utils.cs::CreateFolderMonthNow ", ex);
        throw new Exception(string.Format(Resources.Messages.ERR0066, path), ex);
      }
    }
    /// <summary>
    /// note: path is a virtualpath
    /// </summary>
    /// <param name="path">virtualpath</param>
    public static string CreateFolderYearNow(string path)
    {
      string name = DateTime.Now.ToString("yyyy");
      System.Web.HttpServerUtility server = System.Web.HttpContext.Current.Server;

      if (!DirectoryIsExisted(path))
        throw new Exception(string.Format(Resources.Messages.ERR0066, path));
      path += "/" + name;
      if (DirectoryIsExisted(path))
        return name;
      path = server.MapPath(path);
      try
      {
        Directory.CreateDirectory(path);
        return name;
      }
      catch (Exception ex)
      {
        WriteLog("Utils.cs::CreateFolderYearNow ", ex);
        throw new Exception(string.Format(Resources.Messages.ERR0066, path), ex);
      }
    }
    #endregion

    public static void DeleteFile(string filePath)
    {
      try
      {
        if (File.Exists(filePath))
        {
          File.Delete(filePath);
        }
      }
      catch (Exception ex)
      {
        WriteLog("Utils.cs::Save File From Temp", ex);
      }
    }

    public static string GetFileExtension(string fileName)
    {
      int index = fileName.LastIndexOf(".");
      return fileName.Substring(index);
    }
    #endregion

    #region Email & Url

    public static bool ValidateEmail(string email)
    {
      Regex validator = new Regex(GlobalCache.Instance.EmailRegularExpressions);
      return validator.IsMatch(email);
    }
    public static bool ValidateUrl(string url)
    {
      Regex validator = new Regex(WebRegularExpression);
      return validator.IsMatch(url);
    }
    #endregion
  }
}
